package com.team5.reptiles;

import com.team5.entity.News;
import com.team5.mapper.NewsMapper;
import org.apache.bcel.generic.NEW;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class SecuritiesNews {
    @Autowired
    NewsMapper newsMapper;
    private static final String CHROME_DRIVER_PATH = "C:\\Users\\86155\\Desktop\\chrome-win64\\chromedriver.exe"; // Chromedriver路径
    private static final Logger logger = LoggerFactory.getLogger(SecuritiesNews.class);
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 0/10 * * * ?") // 每10分钟执行一次
    public void fetchAndWriteNews() {
        newsMapper.deleteAll();
        // 设置 ChromeDriver 路径
        System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);

        // 配置 ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless"); // 启用无头模式
        options.addArguments("--disable-gpu"); // 适用于Windows OS
        options.addArguments("--no-sandbox");

        // 初始化 WebDriver
        WebDriver driver = new ChromeDriver(options);

        long startTime = System.currentTimeMillis();
        long endTime = 0;
        int logId = LogIdGenerator.getNextLogId(); // 获取日志ID

        try {
            // 连接到目标网站
            String url = "https://kuaixun.eastmoney.com/";
            driver.get(url);

            // 等待页面加载
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

            // 获取页面HTML
            String pageSource = driver.getPageSource();

            // 使用 JSoup 解析 HTML
            Document doc = Jsoup.parse(pageSource);

            // 获取包含新闻的容器
            Elements newsContainers = doc.select(".news_item");

            // 遍历新闻容器，将标题和时间输出到控制台
            for (Element container : newsContainers) {
                Element newsTime = container.selectFirst(".news_time");
                Element newsDetail = container.selectFirst(".news_detail_txt");
                if (newsTime != null && newsDetail != null) {
                    Element titleElement = newsDetail.selectFirst("span> b");
                    if (titleElement != null) {
                        String spanClass = titleElement.parent().className();
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                        if (spanClass.equals("news_detail_text")){
                            String pic = "news";
                            String title = titleElement.text();
                            String time = newsTime.text();
                            //
                            Date timeOnlyDate = sdf.parse(time);
                            News news=new News();
                            news.setTitle(title);
                            news.setTime(timeOnlyDate);
                            //news.setTime(fullDateTime);
                            news.setPic(pic);
                            newsMapper.insert(news);
                            //
                        }
                        else {
                            String pic = "tips";
                            String title = titleElement.text();
                            String time = newsTime.text();
                            //
                            Date timeOnlyDate = sdf.parse(time);
                            News news=new News();
                            news.setTitle(title);
                            news.setTime(timeOnlyDate);
                            news.setPic(pic);
                            newsMapper.insert(news);
                            //
                        }
                    }
                }
            }

            endTime = System.currentTimeMillis();
            // 记录日志
            String logMessageEnd = "日志ID: " + logId +
                    "，爬虫行为说明: 抓取证券快讯数据" +
                    ", 爬虫网址: https://kuaixun.eastmoney.com/"+
                    "，爬虫开始时间: " + dateFormat.format(new Date(startTime)) +
                    "，爬虫结束时间: " + dateFormat.format(new Date(endTime)) +
                    "，爬虫数据表: 证券快讯";
            logger.info(logMessageEnd);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭 WebDriver
            if (driver != null) {
                driver.quit();
            }
        }
    }
}
